import BlockButton from '@/components/BlockButton';
import SelectRadios from '@/components/SelectRadios';
import TextInput from '@/components/TextInput';
import { SEX_OPTIONS, SEX_VALUE } from '@/configs/options.config';
import { AppContext } from '@/store/index.context';
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { AthletesContext } from '../index.context';
import classes from './index.module.css';
import { nanoid } from 'nanoid';

export default function AddPerson() {
  const [name, setName] = useState('');
  const [sex, setSex] = useState<SEX_VALUE | undefined>(SEX_VALUE.MALE);
  const [birthday, setBirthday] = useState('');
  const { setShowAddDialog, editPerson } = useContext(AthletesContext);
  const { personStore } = useContext(AppContext);

  const handleConfirm = useCallback(
    function () {
      if (editPerson) {
        personStore.mutatePerson({ ...editPerson, name, sex, birthday });
      } else {
        personStore.addPerson({
          name,
          sex,
          birthday,
          id: nanoid(),
          gameSize: 0,
          archived: false,
        });
      }
      setShowAddDialog(false);
    },
    [name, birthday, sex, personStore, setShowAddDialog, editPerson],
  );

  useEffect(
    function () {
      if (editPerson) {
        setName(editPerson.name || '');
        setSex(editPerson.sex);
        setBirthday(editPerson.birthday || '');
      }
    },
    [editPerson],
  );

  return (
    <div className={classes.AddPerson}>
      <TextInput label="昵称：" value={name} onChange={val => setName(val)} />
      <SelectRadios
        label="性别："
        options={SEX_OPTIONS}
        value={sex}
        onChange={val => setSex(val)}
      />
      <TextInput
        label="生日："
        placeholder="请输入生日"
        value={birthday}
        onChange={val => setBirthday(val)}
      />
      <div className={classes.AddFooter}>
        <BlockButton text="取消" onClick={() => setShowAddDialog(false)} />
        <BlockButton type="primary" text="确认" onClick={handleConfirm} />
      </div>
    </div>
  );
}
